package example.demo.juc;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.Timer;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class LockInterruptTest {
    /**
     * 演示lock.lockInterruptibly()拿到锁之后，会不会响应中断，答案不会
     * ，没拿到锁的，就会响应中断，报异常
     */
    @Test
    public void test01() {
        Thread mainThread = Thread.currentThread();
        Lock lock = new ReentrantLock();
        try {
            //拿到锁之后，lockInterruptibly不会响应中断
            lock.lockInterruptibly();
            new Thread(() -> {
                try {
                    Thread.sleep(1000);
                    log.info("打断main线程");
                    mainThread.interrupt();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
            //会相应中断，相应中断就报异常，且把中断标志位设为false
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            log.info(e.getMessage());
            log.info("中断标志位--" + Thread.interrupted());
        } finally {
            lock.unlock();
        }
    }

    @Test
    public void test02() {
        Thread mainThread = Thread.currentThread();

        Lock lock = new ReentrantLock();
        new Thread(() -> {
            lock.lock();
            log.info("拿到锁了");
            try {
                //确保main-park
                Thread.sleep(1000);
                LockSupport.unpark(mainThread);
                //确保main-unpark之后在打断main
                Thread.sleep(1000);
                log.info("打断main线程");
                mainThread.interrupt();
                TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
            } catch (Exception exception) {
                exception.printStackTrace();
            } finally {
                lock.unlock();
                log.info("解锁");
            }
        }, "AAA").start();
        LockSupport.park();
        try {
            //没拿到锁，lockInterruptibly会响应中断，报异常，中断标志位fasle
            lock.lockInterruptibly();
            lock.unlock();
        } catch (InterruptedException e) {
            log.info(e.getMessage());
            log.info("中断标志位--" + Thread.interrupted());
        }
    }
}
